import 'package:library_base/constant/constant.dart';
import 'package:library_base/entities/in_order_page_detail_child_entity.dart';
import 'package:library_base/entities/in_order_page_entity.dart';
import 'package:library_base/entities/in_order_page_goods_details_entity.dart';
import 'package:library_base/global/multi_language.dart';
import 'package:library_base/net/apis.dart';
import 'package:library_base/network/http_config.dart';
import 'package:library_base/provider/base_list_controller.dart';
import 'package:library_base/route/routers.dart';
import 'package:library_base/utils/num_util.dart';
import 'package:library_base/utils/toast_util.dart';
import 'package:library_base/widget/dialog/dialog_util.dart';
import 'package:library_base/widget/multi_state_widget/multi_state_widget.dart';
import 'package:get/get.dart';

class IncomingOrdersDetailController extends BaseListController<
    InOrderPageDetailEntity, InOrderPageDetailChildEntity> {
  late String stockInId;

  late String warehouseId;

  ///应收数量
  double totalCount = 0.0;

  ///应收数量
  double actualCount = 0.0;

  ///是否可以打印|收货完成
  bool enable = false;

  late Function() callback;

  @override
  void onCreate() {
    enableLoadMore = false;
    isShowNoMoreFooter = false;
    stockInId = getArguments()['stockInId'];
    callback = getArguments()['callback'];
  }

  @override
  Future requestData() {
    isFirstLoading = true;
    requestGeneralListData(Apis.IN_ORDER_DETAIL,
        isRefresh: false,
        method: FBResultFul.GET,
        queryParameters: {
          "stockInId": stockInId,
        });
    return super.requestData();
  }

  @override
  List<InOrderPageDetailChildEntity> transformObject(
      InOrderPageDetailEntity data, bool isRefresh) {
    warehouseId = data.warehouseId;
    totalCount = 0.0;
    actualCount = 0.0;
    for (int i = 0; i < data.details.length; i++) {
      var detail = data.details[i];
      totalCount = NumUtil.add(totalCount, detail.purchaseCount);
      if(detail.singleEntry){
        for (int j = 0; j < detail.goodsDetails.length; j++) {
          if (detail.goodsDetails[j].stockInWeight > 0) {
            actualCount++;
          }
        }
      }else{
        actualCount = NumUtil.add(actualCount, detail.stockInCount);
      }
    }
    return data.details;
  }

  @override
  void loadAfter() {
    enable = isEnable();
  }

  @override
  Future onRefreshCallback() async {
    requestGeneralListData(Apis.IN_ORDER_DETAIL,
        isRefresh: true,
        method: FBResultFul.GET,
        queryParameters: {
          "stockInId": stockInId,
        });
  }

  @override
  Future onLoadCallback() async {
    requestGeneralListData(Apis.IN_ORDER_DETAIL,
        isRefresh: false,
        method: FBResultFul.GET,
        queryParameters: {
          "stockInId": stockInId,
        });
  }

  void reset() {
    isFirstLoading = true;
    multiControllerOut.viewStateChange(MultiStateStatus.loading);
    baseState?.setStateCallBack?.call();
    requestGeneralListData(Apis.IN_ORDER_DETAIL,
        isRefresh: false,
        method: FBResultFul.GET,
        queryParameters: {
          "stockInId": stockInId,
        });
  }

  void tryReLoad() {
    isFirstLoading = true;
    multiControllerOut.viewStateChange(MultiStateStatus.loading);
    baseState?.setStateCallBack?.call();
    requestGeneralListData(Apis.IN_ORDER_DETAIL,
        isRefresh: false,
        method: FBResultFul.GET,
        queryParameters: {
          "stockInId": stockInId,
        });
  }

  void singleHeadEntry(InOrderPageDetailChildEntity itemData, int position) {
    var temporary = List<InOrderPageGoodsDetailsEntity>.generate(
        itemData.goodsDetails.length, (int index) {
      return itemData.goodsDetails[index];
    }, growable: true);
    Get.toNamed(Routers.WMS_SINGLE_HEAD_ENTRY_PAGE, arguments: {
      'data': temporary,
      'index': position,
      'stockInId': stockInId,
      'goodsCode': itemData.goodsCode,
      'locationId': itemData.locationId,
      'locationName': itemData.locationName,
      'differenceReason': itemData.differenceReason,
      'serviceUnit': itemData.unit,
      'callback': updatePosition
    });
  }

  void noSingleHeadEntry(InOrderPageDetailChildEntity itemData, int position) {
    var temporary = List<InOrderPageGoodsDetailsEntity>.generate(
        itemData.goodsDetails.length, (int index) {
      return itemData.goodsDetails[index];
    }, growable: true);

    String? locationId = Constant.isShowSeat?itemData.locationId:"1981608491541632";
    String? locationName = Constant.isShowSeat?itemData.locationName:"A001";

    DialogUtil.showCreateWmsNoSingleDialog(arguments: {
      "productName":itemData.goodsName,
      "serviceUnit":itemData.unit,
      'goodsDetails': temporary,
      'position': position,
      'stockInId': stockInId,
      'warehouseId': warehouseId,
      'goodsCode': itemData.goodsCode,
      'locationId': locationId,
      'locationName': locationName,
      'stockInCount': itemData.stockInCount,
      'stockInWeight': itemData.stockInWeight,
      'differenceReason': itemData.differenceReason,
      'updatePosition': updatePositionNoSingleEntry
    });
  }

  void updatePosition(
      int position, List<InOrderPageGoodsDetailsEntity> listDetails,String locationId,String locationName,String? differenceReason) {
    listData.value[position].goodsDetails = listDetails;
    listData.value[position].differenceReason = differenceReason;
    listData.value[position].locationId = locationId;
    listData.value[position].locationName = locationName;
    actualCount = calculateActualCount();
    enable = isEnable();
    baseState!.setState(() {});
  }

  void updatePositionNoSingleEntry(
      int position, List<InOrderPageGoodsDetailsEntity> listDetails,String locationId,String locationName,String? differenceReason,double stockInCount,double stockInWeight) {
    listData.value[position].goodsDetails = listDetails;
    listData.value[position].differenceReason = differenceReason;
    listData.value[position].locationId = locationId;
    listData.value[position].locationName = locationName;
    listData.value[position].stockInCount = stockInCount;
    listData.value[position].stockInWeight = stockInWeight;
    actualCount = calculateActualCount();
    enable = isEnable();
    baseState!.setState(() {});
  }

  bool isEnable() {
    for (int i = 0; i < listData.length; i++) {
      var detail = listData[i];
      if(detail.singleEntry){
        for (int j = 0; j < detail.goodsDetails.length; j++) {
          if (detail.goodsDetails[j].stockInWeight <= 0.0) {
            return false;
          }
        }
      }else{
        if(detail.stockInWeight<=0.0){
          return false;
        }
        if(detail.stockInCount<=0.0){
          return false;
        }
      }
    }
    return true;
  }

  ///计算实际数量
  double calculateActualCount() {
    double temporaryActualCount = 0.0;
    for (int i = 0; i < listData.length; i++) {
      var detail = listData[i];
      if(detail.singleEntry){
        for (int j = 0; j < detail.goodsDetails.length; j++) {
          if (detail.stockInWeight > 0) {
            temporaryActualCount++;
          }
        }
      }else{
        temporaryActualCount = NumUtil.add(temporaryActualCount, detail.stockInCount);
      }
    }
    return temporaryActualCount;
  }

  void goodsFinish() {
    requestUniversal<bool>(Apis.STOCK_IN_FINISH,
        tipSuccess: MultiLanguage.goodsFinish.tr,
        params: {
      "id": stockInId,
    }, resultSuccessCall: (result) async {
      callback();
      Get.back();
    });
  }

  void print() {
    ToastUtil.success(MultiLanguage.featureNotYetAvailable.tr);
  }
}
